<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class EmailController extends Controller
{
    public function __invoke()
    {
        $email = request('email');
        $admin = Admin::where(compact('email'))->first();
        if (!$admin) return $this->fail('邮箱错误或不存在');

        $code = mt_rand(100000, 999999);
        $expired = time() + 300;
        // 缓存验证码
        Cache::add('mail:code:' . $code, compact('code', 'expired'), 5 * 60);

        $title = '重置密码邮件';
        $name = env('APP_NAME');
        $text = "[{$name}] 您的验证码为：{$code}，请在 5 分钟内输入。如非本人操作，请忽略本邮件。";

        try {
            Mail::raw($text, function (Message $message) use ($email, $title) {
                // 发给 $email, 主题为 $title
                $message->to($email)->subject($title);
            });
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            if (!Str::contains($message, 'OpenSSL')) {
                logger('[邮件发送失败]', [$e->getMessage()]);
                return $this->fail('邮件发送失败');
            }
        }

        return $this->successful(compact('email', 'text'));
    }
}
